#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename: capture_get_dir_count.py
# Author: ChenChangSong
# Date: 2025-08-24
"""
功能描述: 获取测试用例目录下的用例数量
注意：目录不全
"""

import sys
import os
import urllib.parse  # 用于URL编码
from typing import List, Dict
from comm.common_code import *

def __tcases_get_dir_str():
    """获取目录树，并组成id字符串"""
    excel_data = get_excel_data()

    url = f"https://www.tapd.cn//api/entity/filter/get_fields?from=tcase&workspace_id={excel_data['项目ID']}&selected_workspace_id={excel_data['项目ID']}&with_workitem_type_status_map=0"
    payload={}
    headers = {
        'accept': '*/*',
        'accept-language': 'zh-CN,zh;q=0.9',
        'priority': 'u=1, i',
        'referer': f'https://www.tapd.cn/{excel_data["项目ID"]}/sparrow/tcase/tcase_list',
        'sec-ch-ua': '"Not;A=Brand";v="99", "Google Chrome";v="139", "Chromium";v="139"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36',
        'x-requested-with': 'XMLHttpRequest',
        'Cookie': excel_data['Cookie']
        }
    response_code, response = api_request(method="GET", url=url, headers=headers, data=payload)
    logger.info(f"响应内容: {response}")
     # 获取目录树数据
    tree_data = response['data']['fields']['category_id']['tree']
    
    # 初始化ID列表，首先添加0
    ids_list = ['0']
    
    # 遍历目录树，提取所有ID
    for node in tree_data:
        ids_list.append(node['id'])
    
    # 将ID列表用%2C连接
    ids_str = "%2C".join(ids_list)
    
    # 组合成最终字符串
    result_str = "data%5BFilter%5D%5Bname%5D=&data%5Bcategory_ids%5D=" + ids_str
    logger.info(f"目录树ID字符串: {result_str}")
    return result_str

def capture_get_dir_count():
    """获取目录树下的用例数量"""
    excel_data = get_excel_data()
    url = f"https://www.tapd.cn/{excel_data["项目ID"]}/sparrow/tcase_categories/get_category_count?t=1756643870916"

    # payload = "data%5BFilter%5D%5Bname%5D=&data%5Bcategory_ids%5D=0%2C1148433040001001295%2C1148433040001001297%2C1148433040001001299%2C1148433040001001300%2C1148433040001001301%2C1148433040001001303%2C1148433040001001304%2C1148433040001001305%2C1148433040001001307%2C1148433040001001308%2C1148433040001001309%2C1148433040001001310%2C1148433040001001312%2C1148433040001001313%2C1148433040001001314%2C1148433040001001315%2C1148433040001001316%2C1148433040001001318%2C1148433040001001319%2C1148433040001001320%2C1148433040001001321%2C1148433040001001322%2C1148433040001001323%2C1148433040001001325%2C1148433040001001326%2C1148433040001001327%2C1148433040001001328%2C1148433040001001329%2C1148433040001001330%2C1148433040001001331%2C1148433040001001333%2C1148433040001001334%2C1148433040001001335%2C1148433040001001336%2C1148433040001001337%2C-1%2C1148433040001001293%2C1148433040001001296%2C1148433040001001302%2C1148433040001001294%2C1148433040001001306%2C1148433040001001298%2C1148433040001001311%2C1148433040001001317%2C1148433040001001332%2C1148433040001001324"
    payload = __tcases_get_dir_str()
    headers = {
    'authority': 'www.tapd.cn',
    'accept': '*/*',
    'accept-language': 'zh-CN,zh;q=0.9',
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'cookie': excel_data['Cookie'],
    'dsc-token': 'C1sAf81eF4cmfWN2',
    'origin': 'https://www.tapd.cn',
    'referer': f'https://www.tapd.cn/{excel_data["项目ID"]}/sparrow/tcase/tcase_list?data[Filter][name]=&async=1&category_id=0&select_workspace={excel_data["项目ID"]}',
    'sec-ch-ua': '"Not)A;Brand";v="24", "Chromium";v="116"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'empty',
    'sec-fetch-mode': 'cors',
    'sec-fetch-site': 'same-origin',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.5845.97 Safari/537.36 Core/1.116.554.400 QQBrowser/19.5.6663.400',
    'x-requested-with': 'XMLHttpRequest'
    }
    response_code, response = api_request(method="GET", url=url, headers=headers, data=payload)
    
    if response_code == 200:
        logger.info(f'↑↑↑=================================================↑↑↑')
        logger.info(f"响应内容: {response}")
        
        # 添加响应内容类型检查
        if isinstance(response, str):
            try:
                # 如果是字符串，尝试解析为JSON
                import json
                response = json.loads(response)
            except json.JSONDecodeError:
                logger.error("响应内容是字符串，但无法解析为JSON")
                return None
        
        return response  # 确保这里返回的是字典
    else:
        logger.error(f"请求失败，状态码: {response_code}")
        logger.error(f"响应内容: {response}")
        logger.info(f'↑↑↑=================================================↑↑↑')
        return None
if __name__ == "__main__":
    capture_get_dir_count()
